#include <time.h>
#include "seqiot.h"
#include "model.h"
#include "sqlite.h"

#define SQL_UPLINK_COLS "id,name,payload_type,ip_host,ip_port,is_ssl,timeout,heartbeat,username,password,client_id,product_key,device_key,device_secret,unit_addr"

uplink_t *uplink_new() {
    return z_calloc(1, sizeof(uplink_t));
}

void uplink_free(uplink_t *uplink) {
    if (!uplink) return;

    z_free(uplink);
}

void read_row_uplink(sqlite3_stmt *stmt, uplink_t *rs) {
    int idx = 2;
    read_row_object(stmt, &rs->super);

//rs->type = sqlite3_column_int(stmt, idx++);
    rs->payload = sqlite3_column_int(stmt, idx++);

    read_row_str(stmt, idx++, rs->remote_address.addr, sizeof(rs->remote_address.addr));
    rs->remote_address.port = sqlite3_column_int(stmt, idx++);
    rs->ssl = sqlite3_column_int(stmt, idx++);
    rs->timeout = sqlite3_column_int(stmt, idx++);
    if (0 == rs->timeout) rs->timeout = 3;
    rs->heartbeat = sqlite3_column_int(stmt, idx++);
    if (0 == rs->heartbeat) rs->heartbeat = 1;

    read_row_str(stmt, idx++, rs->username, sizeof(rs->username));
    read_row_str(stmt, idx++, rs->password, sizeof(rs->password));

    read_row_str(stmt, idx++, rs->client_id, sizeof(rs->client_id));
    read_row_str(stmt, idx++, rs->product_key, sizeof(rs->product_key));
    read_row_str(stmt, idx++, rs->device_key, sizeof(rs->device_key));
    read_row_str(stmt, idx++, rs->device_secret, sizeof(rs->device_secret));
    rs->rtu = sqlite3_column_int(stmt, idx++);
    if (0 == rs->rtu) rs->rtu = 1;
}

static int _read_stmt_uplinks(sqlite3 *db, const char *sql, vector_t *uplinks) {
    int rc;
    sqlite3_stmt *stmt = NULL;

    rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
    if (SQLITE_OK != rc) {
        sqlite_check(db);
        goto err;
    }

    while (SQLITE_ROW == sqlite3_step(stmt)) {
        uplink_t *uplink = uplink_new();
        read_row_uplink(stmt, uplink);
        vector_add(uplinks, uplink);
    }

    err:
    sqlite3_finalize(stmt);
    return rc;
}

int read_stmt_uplink(sqlite3 *db, vector_t *uplinks, obj_id id) {
    char sql[1024];
    sprintf(sql, "SELECT %s FROM mqtt WHERE %s AND id=%d", SQL_UPLINK_COLS, SQL_DISABLE, id);
    return _read_stmt_uplinks(db, sql, uplinks);
}

int read_stmt_uplinks(sqlite3 *db, vector_t *uplinks) {
    char sql[1024];
    sprintf(sql, "SELECT %s FROM mqtt WHERE %s", SQL_UPLINK_COLS, SQL_DISABLE);
    return _read_stmt_uplinks(db, sql, uplinks);
}